package com.ailesson.user.controller;

import com.ailesson.common.reply.R;
import com.ailesson.user.service.WechatMessageService;
import com.ailesson.user.util.SHA1Util;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import me.chanjar.weixin.common.error.WxErrorException;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公众号消息
 *
 * @author mac
 * @email mac@gmail.com
 * @date 2024-10-19 22:39:15
 */
@Tag(name = "公众号消息模块")
@RestController
@RequestMapping("/api/wechat/message")
public class WechatMessageController {

    private static final String TOKEN = "ailesson";

    @Autowired
    private WechatMessageService wechatMessageService;

    @Operation(summary = "推送支付消息")
    @Parameter(name = "id",description = "订单ID")
    @GetMapping("/pushPayMessage")
    public R pushPayMessage(String id) {
        wechatMessageService.pushPayMessage(id);
        return R.success();
    }

    /**
     * 服务器有效性验证
     * @param request
     * @return
     */
    @Operation(summary = "服务器有效性验证")
    @GetMapping
    public String verifyToken(HttpServletRequest request) {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        if (this.checkSignature(signature, timestamp, nonce)) {
            return echostr;
        }
        return echostr;
    }
    private boolean checkSignature(String signature, String timestamp, String nonce) {
        String[] str = new String[]{TOKEN, timestamp, nonce};
        //排序
        Arrays.sort(str);
        //拼接字符串
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < str.length; i++) {
            buffer.append(str[i]);
        }
        //进行sha1加密
        String temp = SHA1Util.encode(buffer.toString());
        //与微信提供的signature进行匹对
        return signature.equals(temp);
    }

    /**
     * 接收微信服务器发送来的消息
     * @param request
     * @return
     * @throws Exception
     */
    @Operation(summary = "接收微信服务器发送来的消息")
    @PostMapping
    public String receiveMessage(HttpServletRequest request) {
        Map<String, String> param = this.parseXml(request);
        String message = wechatMessageService.receiveMessage(param);
        return message;
    }

    private Map<String, String> parseXml(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            Element root = document.getRootElement();
            List<Element> elementList = root.elements();
            for (Element e : elementList) {
                map.put(e.getName(), e.getText());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            if (inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
                inputStream = null;
            }
        }
        return map;
    }



}
